package com.flickr.tasks;

import java.io.InputStream;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import com.flickr.utils.IOUtils;


public final class BitmapLoaderTask extends AsyncTask<Void, Void, Bitmap>
{
    private static final String TAG = BitmapLoaderTask.class.getSimpleName();

    private final URL mImageUrl;
    private final ImageView mImageView;
    private final int mSampleSize;

    public BitmapLoaderTask(URL imageUrl, ImageView imageView, int sampleSize) {
        mImageUrl = imageUrl;
        mImageView = imageView;
        mSampleSize = sampleSize;
    }
    
    public BitmapLoaderTask(URL imageUrl, ImageView imageView) {
        this(imageUrl, imageView, 1);
    }
    
    @Override
    protected Bitmap doInBackground(Void... params)
    {
        InputStream is = null;
        try {
            is = mImageUrl.openStream();
            
            Options options = new Options();
            options.inSampleSize = mSampleSize;
            return BitmapFactory.decodeStream(is, null, options);
            
        } catch(Exception ex) {
            Log.e(TAG, "Error loading image at URL: " + mImageUrl, ex);
            return null;
            
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    
    @Override
    protected void onPostExecute(Bitmap result)
    {
        if(result != null) {
            mImageView.setImageBitmap(result);
        } else {
            mImageView.setImageDrawable(null);
        }
    }
    
}
